<template>
  <div class="outbound-management">
    <div class="page-header">
      <h2>出库管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索条件区域 -->
    <el-card class="search-card">
      <template #header>
        <span>搜索条件</span>
        <el-button type="text" @click="resetSearch" style="float: right;">重置</el-button>
      </template>
      
      <el-form :model="searchForm" inline class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="客户代码">
              <el-select v-model="searchForm.customerCode" filterable
                         placeholder="选择客户代码" clearable style="width: 100%;"
                         @change="handleSearchCustomerCodeChange">
                <el-option v-for="customer in customers" :key="customer.customerCode"
                          :label="customer.customerCode" :value="customer.customerCode"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称">
              <el-select v-model="searchForm.customerName" filterable
                         placeholder="选择客户名称" clearable style="width: 100%;"
                         @change="handleSearchCustomerNameChange">
                <el-option v-for="customer in customers" :key="customer.customerName"
                          :label="customer.customerName" :value="customer.customerName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品名称">
              <el-input v-model="searchForm.productName" placeholder="产品名称" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料编码">
              <el-input v-model="searchForm.materialCode" placeholder="物料编码" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="厂内编号">
              <el-input v-model="searchForm.factoryNo" placeholder="厂内编号" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务员">
              <el-select v-model="searchForm.salesperson" filterable allow-create default-first-option
                         placeholder="选择或输入业务员" clearable style="width: 100%;">
                <el-option v-for="emp in employees" :key="emp.employeeCode" 
                          :label="emp.employeeName" :value="emp.employeeName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库日期">
              <el-date-picker 
                v-model="searchForm.dateRange" 
                type="daterange" 
                range-separator="至" 
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="库存状态">
              <el-select v-model="searchForm.status" placeholder="选择库存状态" clearable style="width: 100%;">
                <el-option label="有库存" value="有库存"/>
                <el-option label="库存预警" value="预警"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" style="text-align: center;">
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><RefreshLeft /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 可出库库存列表 -->
    <el-card class="table-card">
      <template #header>
        <span>可出库库存列表</span>
        <span style="color: #999; font-size: 14px; margin-left: 10px;">
          (显示当前有库存的物料)
        </span>
      </template>

      <el-table 
        :data="stockList" 
        border 
        v-loading="loading"
        height="500"
        style="width: 100%">
        
        <el-table-column type="index" label="序号" width="60" fixed="left"/>
        
        <el-table-column prop="customerCode" label="客户代码" width="100" fixed="left"/>
        <el-table-column prop="customerName" label="客户名称" width="120" fixed="left"/>
        <el-table-column prop="factoryNo" label="厂内编号" width="100" fixed="left"/>
        <el-table-column prop="productName" label="产品名称" width="150" fixed="left" show-overflow-tooltip/>
        
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openOutboundDialog(row)">
              出库
            </el-button>
          </template>
        </el-table-column>
        
        <el-table-column prop="materialCode" label="物料编码" width="120" show-overflow-tooltip/>
        <el-table-column prop="layers" label="层数" width="80"/>
        <el-table-column prop="thickness" label="板厚" width="80"/>
        <el-table-column prop="surfaceTreatment" label="表面处理" width="100"/>
        <el-table-column prop="solderMask" label="阻焊" width="80"/>
        <el-table-column prop="character" label="字符" width="80"/>
        <el-table-column prop="boardMaterial" label="板材" width="100"/>
        <el-table-column prop="deliverySize" label="交货尺寸" width="120"/>
        <el-table-column prop="totalInboundQuantity" label="总入库数量" width="110"/>
        <el-table-column prop="totalOutboundQuantity" label="总出库数量" width="110"/>
        <el-table-column prop="currentStockQuantity" label="当前库存" width="100">
          <template #default="{ row }">
            <span style="color: #67C23A; font-weight: bold;">{{ row.currentStockQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="spareQuantity" label="备品数量" width="100"/>
        <el-table-column prop="unitPrice" label="单价" width="100">
          <template #default="{ row }">
            <span v-if="row.unitPrice">{{ row.unitPrice.toFixed(4) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="库存总金额" width="120">
          <template #default="{ row }">
            <span v-if="row.totalAmount" style="color: #E6A23C; font-weight: bold;">
              ¥{{ row.totalAmount.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="lastInboundDate" label="最后入库日期" width="130"/>
        <el-table-column prop="lastOutboundDate" label="最后出库日期" width="130"/>
        <el-table-column prop="status" label="库存状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="salesperson" label="业务员" width="100"/>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>

    <!-- 出库操作弹窗 -->
    <el-dialog 
      v-model="outboundDialogVisible" 
      title="出库操作" 
      width="1000px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      class="outbound-dialog">
      
      <div class="outbound-form-container">
        <!-- 基本信息区域 -->
        <el-card shadow="never" class="form-section">
          <template #header>
            <div class="section-header">
              <el-icon><InfoFilled /></el-icon>
              <span>基本信息</span>
            </div>
          </template>
          
          <el-form :model="outboundForm" :rules="outboundRules" ref="outboundFormRef" label-width="120px">
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="客户代码" prop="customerCode">
                  <el-select 
                    v-model="outboundForm.customerCode" 
                    placeholder="请选择客户代码"
                    filterable
                    allow-create
                    style="width: 100%"
                    @change="handleCustomerCodeChange">
                    <el-option
                      v-for="customer in customers"
                      :key="customer.customerCode"
                      :label="customer.customerCode"
                      :value="customer.customerCode">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户名称" prop="customerName">
                  <el-select 
                    v-model="outboundForm.customerName" 
                    placeholder="请选择客户名称"
                    filterable
                    allow-create
                    style="width: 100%"
                    @change="handleCustomerNameChange">
                    <el-option
                      v-for="customer in customers"
                      :key="customer.customerName"
                      :label="customer.customerName"
                      :value="customer.customerName">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="厂内编号" prop="factoryNo">
                  <el-input 
                    v-model="outboundForm.factoryNo" 
                    placeholder="请输入厂内编号"
                    style="width: 100%"/>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="产品名称" prop="productName">
                  <el-input 
                    v-model="outboundForm.productName" 
                    placeholder="请输入产品名称"
                    style="width: 100%"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物料编码">
                  <el-input 
                    v-model="outboundForm.materialCode" 
                    readonly 
                    class="readonly-input"
                    style="width: 100%"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <!-- 产品规格信息区域 -->
        <el-card shadow="never" class="form-section">
          <template #header>
            <div class="section-header">
              <el-icon><Grid /></el-icon>
              <span>产品规格</span>
            </div>
          </template>
          
          <el-form :model="outboundForm" label-width="120px">
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="层数">
                  <el-input v-model="outboundForm.layers" readonly class="readonly-input">
                    <template #append>层</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="板厚">
                  <el-input v-model="outboundForm.thickness" readonly class="readonly-input">
                    <template #append>mm</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="交货尺寸">
                  <el-input v-model="outboundForm.deliverySize" readonly class="readonly-input">
                    <template #append>mm</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="表面处理">
                  <el-input v-model="outboundForm.surfaceTreatment" readonly class="readonly-input"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="阻焊">
                  <el-input v-model="outboundForm.solderMask" readonly class="readonly-input"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="字符">
                  <el-input v-model="outboundForm.character" readonly class="readonly-input"/>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="板材">
                  <el-input v-model="outboundForm.boardMaterial" readonly class="readonly-input"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="业务员">
                  <el-input v-model="outboundForm.salesperson" readonly class="readonly-input"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <!-- 库存与出库信息区域 -->
        <el-card shadow="never" class="form-section">
          <template #header>
            <div class="section-header">
              <el-icon><Box /></el-icon>
              <span>库存与出库信息</span>
            </div>
          </template>
          
          <el-form :model="outboundForm" :rules="outboundRules" ref="outboundFormRef2" label-width="120px">
            <!-- 库存信息展示 -->
            <div class="stock-info-section">
              <el-row :gutter="20">
                <el-col :span="5">
                  <div class="info-item">
                    <div class="info-label">订单数量</div>
                    <div class="info-value primary">{{ outboundForm.orderQuantity || 0 }} PCS</div>
                  </div>
                </el-col>
                <el-col :span="5">
                  <div class="info-item">
                    <div class="info-label">总入库数量</div>
                    <div class="info-value">{{ outboundForm.totalInboundQuantity || 0 }} PCS</div>
                  </div>
                </el-col>
                <el-col :span="5">
                  <div class="info-item">
                    <div class="info-label">已出库数量</div>
                    <div class="info-value warning">{{ outboundForm.totalOutboundQuantity || 0 }} PCS</div>
                  </div>
                </el-col>
                <el-col :span="5">
                  <div class="info-item">
                    <div class="info-label">当前库存</div>
                    <div class="info-value success">{{ outboundForm.currentStockQuantity || 0 }} PCS</div>
                  </div>
                </el-col>
                <el-col :span="4">
                  <div class="info-item">
                    <div class="info-label">备品数量</div>
                    <div class="info-value">{{ outboundForm.spareQuantityStock || 0 }} PCS</div>
                  </div>
                </el-col>
              </el-row>
              
              <!-- 出库进度条 -->
              <div class="progress-section">
                <div class="progress-label">出库进度</div>
                <el-progress 
                  :percentage="calculateOutboundProgress()" 
                  :color="getProgressColor()"
                  :stroke-width="8"
                  :show-text="true">
                  <template #default="{ percentage }">
                    <span style="color: #606266; font-size: 12px;">
                      {{ percentage }}% ({{ outboundForm.totalOutboundQuantity }}/{{ outboundForm.orderQuantity }})
                    </span>
                  </template>
                </el-progress>
              </div>
            </div>
            
            <!-- 出库操作区域 -->
            <el-divider content-position="left">
              <span style="color: #409eff; font-weight: bold;">出库操作</span>
            </el-divider>
            
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="出库数量" prop="outboundQuantity" class="required-field">
                  <el-input
                    v-model.number="outboundForm.outboundQuantity"
                    type="number"
                    :min="1"
                    :max="outboundForm.currentStockQuantity"
                    placeholder="请输入出库数量"
                    style="width: 100%;">
                    <template #suffix>
                      <span style="color: #999; font-size: 12px;">PCS</span>
                    </template>
                  </el-input>
                  <div class="field-hint">最大可出库：{{ outboundForm.currentStockQuantity }} PCS</div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="备品数量">
                  <el-input
                    v-model.number="outboundForm.spareQuantity"
                    type="number"
                    :min="0"
                    placeholder="请输入备品数量"
                    style="width: 100%;">
                    <template #suffix>
                      <span style="color: #999; font-size: 12px;">PCS</span>
                    </template>
                  </el-input>
                  <div class="field-hint">可选填，通常为出库数量的10%</div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="出库日期" prop="outboundDate" class="required-field">
                  <el-date-picker 
                    v-model="outboundForm.outboundDate" 
                    type="date" 
                    placeholder="选择出库日期"
                    value-format="YYYY-MM-DD"
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="备注信息">
                  <el-input 
                    v-model="outboundForm.remark" 
                    type="textarea" 
                    :rows="3" 
                    placeholder="请输入备注信息（可选）"
                    maxlength="500"
                    show-word-limit
                    style="width: 100%">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="outboundDialogVisible = false" size="large">
            <el-icon><Close /></el-icon>
            取消
          </el-button>
          <el-button type="primary" @click="handleOutbound" :loading="outboundLoading" size="large">
            <el-icon><Check /></el-icon>
            确认出库
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getAvailableStock, 
  createOutbound, 
  getCustomerOptions, 
  getEmployeeOptions 
} from '@/api/warehouse'
import { Search, Refresh, RefreshLeft, InfoFilled, Grid, Box, Close, Check } from '@element-plus/icons-vue'

export default {
  name: 'OutboundManagement',
  components: {
    Search,
    Refresh,
    RefreshLeft,
    InfoFilled,
    Grid,
    Box,
    Close,
    Check
  },
  setup() {
    const loading = ref(false)
    const outboundLoading = ref(false)
    const outboundDialogVisible = ref(false)
    const outboundFormRef = ref()

    // 搜索表单
    const searchForm = reactive({
      customerCode: '',
      customerName: '',
      productName: '',
      materialCode: '',
      factoryNo: '',
      salesperson: '',
      dateRange: [],
      status: ''
    })

    // 出库表单
    const outboundForm = reactive({
      stockId: '',
      customerCode: '',
      customerName: '',
      factoryNo: '',
      productName: '',
      materialCode: '',
      layers: '',
      thickness: '',
      deliverySize: '',
      surfaceTreatment: '',
      solderMask: '',
      character: '',
      boardMaterial: '',
      salesperson: '',
      orderQuantity: 0,
      totalInboundQuantity: 0,
      totalOutboundQuantity: 0,
      currentStockQuantity: 0,
      spareQuantityStock: 0,
      outboundQuantity: '',
      spareQuantity: '',
      outboundDate: new Date().toISOString().split('T')[0],
      remark: ''
    })

    // 出库表单验证规则
    const outboundRules = {
      customerCode: [
        { required: true, message: '客户代码不能为空', trigger: 'blur' }
      ],
      customerName: [
        { required: true, message: '客户名称不能为空', trigger: 'blur' }
      ],
      factoryNo: [
        { required: true, message: '厂内编号不能为空', trigger: 'blur' }
      ],
      productName: [
        { required: true, message: '产品名称不能为空', trigger: 'blur' }
      ],
      currentStockQuantity: [
        { required: true, message: '当前库存不能为空', trigger: 'blur' }
      ],
      outboundQuantity: [
        { required: true, message: '出库数量不能为空', trigger: 'blur' },
        { pattern: /^[1-9]\d*$/, message: '出库数量必须为正整数', trigger: 'blur' }
      ],
      outboundDate: [
        { required: true, message: '出库日期不能为空', trigger: 'change' }
      ]
    }

    // 分页信息
    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    // 库存列表
    const stockList = ref([])
    
    // 基础数据
    const customers = ref([])
    const employees = ref([])

    // 计算属性：搜索参数
    const searchParams = computed(() => {
      const params = {
        current: pagination.current,
        size: pagination.size,
        ...searchForm
      }
      
      // 处理日期范围
      if (searchForm.dateRange && searchForm.dateRange.length === 2) {
        params.startDate = searchForm.dateRange[0]
        params.endDate = searchForm.dateRange[1]
      }
      delete params.dateRange
      
      // 移除空值
      Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
          delete params[key]
        }
      })
      
      return params
    })

    // 获取可出库库存列表
    const fetchStockList = async () => {
      try {
        loading.value = true
        const response = await getAvailableStock(searchParams.value)
        
        if (response.code === 200) {
          stockList.value = response.data.records || []
          pagination.total = response.data.total || 0
        }
      } catch (error) {
        console.error('获取库存列表失败:', error)
        ElMessage.error('获取库存列表失败')
      } finally {
        loading.value = false
      }
    }

    // 获取基础数据
    const fetchBaseData = async () => {
      try {
        const [customerRes, employeeRes] = await Promise.all([
          getCustomerOptions(),
          getEmployeeOptions()
        ])
        
        if (customerRes.code === 200) {
          customers.value = customerRes.data || []
        }
        
        if (employeeRes.code === 200) {
          employees.value = employeeRes.data || []
        }
      } catch (error) {
        console.error('获取基础数据失败:', error)
        ElMessage.error('获取基础数据失败')
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      fetchStockList()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        customerCode: '',
        customerName: '',
        productName: '',
        materialCode: '',
        factoryNo: '',
        salesperson: '',
        dateRange: [],
        status: ''
      })
      pagination.current = 1
      fetchStockList()
    }

    // 刷新数据
    const refreshData = () => {
      fetchStockList()
    }

    // 分页变化
    const handleSizeChange = (val) => {
      pagination.size = val
      pagination.current = 1
      fetchStockList()
    }

    const handleCurrentChange = (val) => {
      pagination.current = val
      fetchStockList()
    }

    // 打开出库弹窗
    const openOutboundDialog = (row) => {
      // 重置表单
      Object.assign(outboundForm, {
        stockId: row.id,
        customerCode: row.customerCode || '',
        customerName: row.customerName || '',
        factoryNo: row.factoryNo || '',
        productName: row.productName || '',
        materialCode: row.materialCode || '',
        layers: row.layers || '',
        thickness: row.thickness || '',
        deliverySize: row.deliverySize || '',
        surfaceTreatment: row.surfaceTreatment || '',
        solderMask: row.solderMask || '',
        character: row.character || '',
        boardMaterial: row.boardMaterial || '',
        salesperson: row.salesperson || '',
        orderQuantity: row.totalInboundQuantity || 0, // 订单数量等于总入库数量
        totalInboundQuantity: row.totalInboundQuantity || 0,
        totalOutboundQuantity: row.totalOutboundQuantity || 0,
        currentStockQuantity: row.currentStockQuantity || 0,
        spareQuantityStock: row.spareQuantity || 0,
        outboundQuantity: '',
        spareQuantity: '',
        outboundDate: new Date().toISOString().split('T')[0],
        remark: ''
      })
      
      outboundDialogVisible.value = true
    }

    // 客户代码变化处理
    const handleCustomerCodeChange = (customerCode) => {
      const customer = customers.value.find(c => c.customerCode === customerCode)
      if (customer) {
        outboundForm.customerName = customer.customerName
      }
    }

    // 客户名称变化处理
    const handleCustomerNameChange = (customerName) => {
      const customer = customers.value.find(c => c.customerName === customerName)
      if (customer) {
        outboundForm.customerCode = customer.customerCode
      }
    }

    // 搜索表单-客户代码变化处理
    const handleSearchCustomerCodeChange = (customerCode) => {
      const customer = customers.value.find(c => c.customerCode === customerCode)
      if (customer) {
        searchForm.customerName = customer.customerName
      }
    }

    // 搜索表单-客户名称变化处理
    const handleSearchCustomerNameChange = (customerName) => {
      const customer = customers.value.find(c => c.customerName === customerName)
      if (customer) {
        searchForm.customerCode = customer.customerCode
      }
    }

    // 执行出库操作
    const handleOutbound = async () => {
      try {
        await outboundFormRef.value.validate()
        
        // 验证出库数量
        const outboundQty = parseInt(outboundForm.outboundQuantity)
        const currentStock = parseInt(outboundForm.currentStockQuantity)
        if (outboundQty > currentStock) {
          ElMessage.error('出库数量不能超过当前库存数量')
          return
        }
        
        await ElMessageBox.confirm(
          `确认对产品"${outboundForm.productName}"执行出库操作吗？\n出库数量: ${outboundForm.outboundQuantity} PCS`,
          '确认出库',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        outboundLoading.value = true
        const response = await createOutbound(outboundForm)
        
        if (response.code === 200) {
          ElMessage.success('出库成功')
          outboundDialogVisible.value = false
          fetchStockList() // 刷新列表
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('出库失败:', error)
          ElMessage.error('出库失败')
        }
      } finally {
        outboundLoading.value = false
      }
    }

    // 获取状态类型
    const getStatusType = (status) => {
      switch (status) {
        case '有库存':
          return 'success'
        case '预警':
          return 'warning'
        case '无库存':
          return 'danger'
        default:
          return 'info'
      }
    }

    // 计算出库进度
    const calculateOutboundProgress = () => {
      const orderQty = outboundForm.orderQuantity || 0
      const outboundQty = outboundForm.totalOutboundQuantity || 0
      if (orderQty === 0) return 0
      const progress = Math.round((outboundQty / orderQty) * 100)
      return Math.min(progress, 100)
    }

    // 获取进度条颜色
    const getProgressColor = () => {
      const progress = calculateOutboundProgress()
      if (progress < 50) {
        return '#67c23a' // 绿色
      } else if (progress < 80) {
        return '#e6a23c' // 橙色
      } else if (progress < 100) {
        return '#f56c6c' // 红色
      } else {
        return '#909399' // 灰色（已完成）
      }
    }

    // 初始化
    onMounted(() => {
      fetchBaseData()
      fetchStockList()
    })

    return {
      loading,
      outboundLoading,
      outboundDialogVisible,
      outboundFormRef,
      searchForm,
      outboundForm,
      outboundRules,
      pagination,
      stockList,
      customers,
      employees,
      handleSearch,
      resetSearch,
      refreshData,
      handleSizeChange,
      handleCurrentChange,
      openOutboundDialog,
      handleOutbound,
      getStatusType,
      handleCustomerCodeChange,
      handleCustomerNameChange,
      handleSearchCustomerCodeChange,
      handleSearchCustomerNameChange,
      calculateOutboundProgress,
      getProgressColor
    }
  }
}
</script>

<style scoped>
.outbound-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-table {
  font-size: 14px;
}

.el-table .el-table__cell {
  padding: 8px 0;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

/* 弹窗样式优化 */
.outbound-dialog :deep(.el-dialog__body) {
  padding: 0 !important;
  max-height: 85vh;
  overflow-y: auto;
}

.outbound-form-container {
  padding: 0;
}

.form-section {
  margin-bottom: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.form-section:last-child {
  margin-bottom: 0;
}

.form-section :deep(.el-card__header) {
  background-color: #fafafa;
  border-bottom: 1px solid #e4e7ed;
  padding: 12px 20px;
}

.form-section :deep(.el-card__body) {
  padding: 20px;
}

.section-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.section-header .el-icon {
  margin-right: 8px;
  color: #409eff;
}

/* 只读输入框样式 */
.readonly-input :deep(.el-input__wrapper) {
  background-color: #f5f7fa !important;
  box-shadow: 0 0 0 1px #dcdfe6 inset !important;
}

.readonly-input :deep(.el-input__inner) {
  color: #606266 !important;
  background-color: transparent !important;
}

/* 库存信息展示区域 */
.stock-info-section {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 20px;
  margin-bottom: 20px;
}

.info-item {
  text-align: center;
  padding: 8px;
}

.info-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 6px;
}

.info-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.info-value.primary {
  color: #409eff;
}

.info-value.success {
  color: #67c23a;
}

.info-value.warning {
  color: #e6a23c;
}

/* 进度条区域 */
.progress-section {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #e9ecef;
}

.progress-label {
  font-size: 12px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

/* 必填字段样式 */
.required-field :deep(.el-form-item__label)::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.required-field :deep(.el-form-item__label) {
  font-weight: 600;
  color: #303133;
}

/* 字段提示 */
.field-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

/* 分隔线样式 */
:deep(.el-divider__text) {
  background-color: #fff;
  font-size: 14px;
}

/* 底部按钮样式 */
.dialog-footer {
  padding: 20px;
  text-align: right;
  border-top: 1px solid #e4e7ed;
  background-color: #fafafa;
}

.dialog-footer .el-button {
  margin-left: 12px;
  min-width: 100px;
  padding: 12px 20px;
}

/* 表单项间距 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}

/* 输入框样式统一 */
:deep(.el-input),
:deep(.el-select),
:deep(.el-date-editor),
:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

/* 数字输入框样式优化 */
:deep(.el-input-number) {
  width: 100% !important;
}

:deep(.el-input-number .el-input__wrapper) {
  width: 100% !important;
}

/* 响应式处理 */
@media (max-width: 1200px) {
  .outbound-dialog :deep(.el-dialog) {
    width: 95% !important;
    margin: 0 auto;
  }
}

@media (max-width: 768px) {
  .outbound-dialog :deep(.el-dialog) {
    width: 98% !important;
    margin: 0 auto;
  }
  
  .form-section :deep(.el-card__body) {
    padding: 15px;
  }
  
  .dialog-footer {
    padding: 15px;
  }
  
  .dialog-footer .el-button {
    min-width: 80px;
    padding: 10px 16px;
  }
}
</style> 